package com.hc.security.jwt;

import com.hc.common.bean.Result;
import com.hc.common.bean.ResultUtil;
import com.hc.common.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 当用户在没有授权的时候，返回的指定信息
 */
@Slf4j
@Component
public class JwtAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws ServletException {
        log.info("用户访问没有授权资源:{}", e.getMessage());

        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try (PrintWriter out = response.getWriter();) {
            Result result = ResultUtil.fail("用户访问未授权资源").setCode(HttpServletResponse.SC_UNAUTHORIZED);
            out.write(JsonUtil.obj2String(result));
            out.flush();
        } catch (IOException exception) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }
}
